﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

namespace OrangePrj
{
    public static class FileReader
    {
        public static Project Open(User currentUser, out String errorMessage)
        {
            errorMessage = String.Empty;
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.ShowDialog();
            BinaryFormatter binFormat = new BinaryFormatter();
            using (Stream fStream = File.OpenRead(dialog.FileName))
            {
                Project project = (Project)binFormat.Deserialize(fStream);
                if (!currentUser.IsAdmin && currentUser.Name != project.user.Name)
                {
                    errorMessage = "У вас не хвататет прав чтобы открыть этот проект";
                    return null;
                }
                return project;
            }
            
        }

        public static void Save(Project project)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.ShowDialog();
            BinaryFormatter binFormat = new BinaryFormatter();
            using (Stream fStream = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                binFormat.Serialize(fStream, project);
            }
            MessageBox.Show("Проект сохранён.", "Сохранение", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        }
    }
}
